import HttpConfig from './httpConfig';
import axios from 'axios';
import Qs from 'qs';
let httpInterface = {};

// 请求地址
import("./request-address/third-party");
import('./request-address/environment');
import("./request-address/vehicle");  // 车辆管理
import("./request-address/home");
import("./request-address/material");
import('./request-address/monitor');
import('./request-address/attendance');  // 考勤管理
import('./request-address/device');
import('./request-address/organize');


function getUserInfo(callback = null) {
  let params = {
    account: "0000:admin",
    password: "123456"
  };
  let config = {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Accept': 'application/json;charset=UTF-8'
    }
  };
  axios.defaults.withCredentials = false;
  axios.post(HttpConfig.serverUrl + "/auth/user/login", Qs.stringify(params), config)
    .then(res => {
      let data = res.data;
      if (data.code == 2000) {
        let tokenData = {
          accessToken: data.data.accessToken,
          accessTokenExpiration: data.data.accessTokenExpiration,
          refreshToken: data.data.refreshToken,
          refreshTokenExpiration: data.data.refreshTokenExpiration
        };
        sessionStorage.setItem('token', JSON.stringify(tokenData));
        callback && callback();
      }
    })
}


function requestGet(vue, path, params, successCallback, failCallback = null) {
  axios.defaults.withCredentials = false;
  var token = JSON.parse(sessionStorage.getItem("token"));
  let config = {
    headers: {
      "Authorization": token == null ? "Bearer" : ("Bearer " + token.accessToken)
    },
    "params": params
  };
  axios.get(HttpConfig.serverUrl + path, config)
    .then(successCallback)
    .catch(function (error) {
      if (!error.response) return;
      let data = error.response.data;
      if (data.code == 1001) {
        refreshToken(vue, path, params, successCallback, failCallback, null, null, "get");
      }
      failCallback && failCallback(error);
    });
}

function requestPost(vue, path, params, successCallback, failCallback = null, isFormData = true) {
  axios.defaults.withCredentials = false;
  var token = JSON.parse(sessionStorage.getItem("token"));
  if (isFormData == true) {
    let config = {};
    if (path === httpInterface.URL_USER_LOGIN) {
      config.headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json;charset=UTF-8'
      };
    } else {
      config.headers = {
        "Authorization": token == null ? "Bearer" : ("Bearer " + token.accessToken),
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json;charset=UTF-8'
      };
    }
    let configObj = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json;charset=UTF-8'
      }
    };
    axios.post(HttpConfig.serverUrl + path, Qs.stringify(params), config)
      .then(successCallback)
      .catch(function (error) {
        if (!error.response) return;
        let data = error.response.data;
        if (data.code == 1001) {
          refreshToken(vue, path, params, successCallback, failCallback, isFormData, configObj, "post");
        }
        failCallback && failCallback(error);
      });
  } else {
    let config = {
      headers: {
        "Authorization": token == null ? "Bearer" : "Bearer " + token.accessToken,
        'Accept': 'application/json;charset=UTF-8'
      }
    };
    let configObj = {
      headers: {
        'Accept': 'application/json;charset=UTF-8'
      }
    };
    axios.post(HttpConfig.serverUrl + path, params, config)
      .then(successCallback)
      .catch(function (error) {
        if (!error.response) return;
        let data = error.response.data;
        if (data.code == 1001) {
          refreshToken(vue, path, params, successCallback, failCallback, isFormData, configObj, "post");
        }
        failCallback && failCallback(error);
      });
  }
}

// 乐橙云接口
function requestPOST(vue, path, params, successCallback, failCallback = null, isFormData = true) {
  axios.defaults.withCredentials = true;
  if (isFormData == true) {
    axios.post("/api" + path, Qs.stringify(params), {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json;charset=UTF-8'
      }
    })
      .then(successCallback)
      .catch(function (error) {
        failCallback && failCallback(error);
      });
  } else {
    axios.post("/api" + path, params)
      .then(successCallback)
      .catch(function (error) {
        failCallback && failCallback(error);
      });
  }
}


// 刷新token
function refreshToken(vue, path, params, successCallback, failCallback, isFormData, config, type) {
  let token = JSON.parse(sessionStorage.getItem("token"));
  axios.get(HttpConfig.serverUrl + httpInterface.URL_USER_REFRESH + "/" + token.refreshToken, null, config)
    .then(res => {
      let { code, data } = res.data;
      let newToken = {};
      if (code == 2000) {
        if (data) {
          newToken = {
            accessToken: data.value,
            accessTokenExpiration: data.expiration,
            refreshToken: data.refreshToken.value,
            refreshTokenExpiration: data.refreshToken.expiration
          };
          sessionStorage.setItem('token', JSON.stringify(newToken));
          if (type === "get") {
            requestGet(vue, path, params, successCallback, failCallback);
          } else {
            requestPost(vue, path, params, successCallback, failCallback, isFormData);
          }
        }
      }
    })
}


function getXialaList(type, callback) {
  var params = { itemname: type };
  httpInterface.requestPost(this, httpInterface.URL_DICT_SELECT_LIST, params, function (res) {
    callback(res.data);
  }, function (e) {
    console.log(e);
  }, false);
}

//工种列表
function getWorkTypeList(callback) {
  getXialaList("worktype", callback);
}

//婚姻状况列表
function getMaritalstatusList(callback) {
  getXialaList("maritalstatus", callback);
}

//用工性质列表
function getWorknatureList(callback) {
  getXialaList("worknature", callback);
}

//血型列表
function getBloodtypeList(callback) {
  getXialaList("bloodtype", callback);
}

//学历列表
function getEdutypeList(callback) {
  getXialaList("edutype", callback);
}

//政治面貌
function getPoliticsstatusList(callback) {
  getXialaList("politicsstatus", callback);
}

httpInterface.requestGet = requestGet;
httpInterface.requestPost = requestPost;
httpInterface.requestPOST = requestPOST;
httpInterface.getUserInfo = getUserInfo;
httpInterface.getWorkTypeList = getWorkTypeList;
httpInterface.getMaritalstatusList = getMaritalstatusList;
httpInterface.getWorknatureList = getWorknatureList;
httpInterface.getBloodtypeList = getBloodtypeList;
httpInterface.getEdutypeList = getEdutypeList;
httpInterface.getPoliticsstatusList = getPoliticsstatusList;


// 登录
httpInterface.URL_USER_LOGIN = "/auth/user/login";  // 用户登录
httpInterface.URL_USER_REFRESH = "/auth/user/refresh";  // 刷新token

// 实时监工
httpInterface.URL_DUTYCOUNT_INDEX = "/dutycount/index";  // 人员统计
httpInterface.URL_DUTYLOG_LIST = "/dutylog/list";  // 出入记录

// 人员信息
httpInterface.URL_DUTYUSER_LIST = "/dutyuser/list";  // 人员列表
httpInterface.URL_UPDATE_PRESENCE = "/dutyuser/updatePresence";  // 人员管理 列表中的是否在场

httpInterface.URL_DUTYUSER_DETAIL = "/dutyuser/detail";//获取用户详情
httpInterface.URL_DUTYUSER_ADDUSER = "/dutyuser/adduser";//添加用户
httpInterface.URL_DUTYUSER_EDIT = "/dutyuser/edit";//修改用户
httpInterface.URL_DUTYUSER_DELETE = "/dutyuser/delete";//删除用户
httpInterface.URL_DUTYUSER_UPDATESTATUS = "/dutyuser/updateStatus";  // 修改用户黑名单和工资发放状态

httpInterface.URL_DICT_SELECT_LIST = "/dict/selectListByName";  // 添加人员的类型列表
httpInterface.URL_ROLE_LIST = "/role/list";  // 角色列表
httpInterface.URL_ROLE_ADD_ROLE = "/role/addrole";  // 添加角色
httpInterface.URL_ROLE_EDIT_SHOW = "/role/editshow";  // 获取角色详情
httpInterface.URL_ROLE_EDIT = "/role/edit";  // 修改角色
httpInterface.URL_ROLE_DEL_ROLE = "/role/delrole";  // 删除角色
httpInterface.URL_DUTYMANAGE_FIND_ORG = "/dutymanage/findOrg";  // 根据标段查组织
httpInterface.URL_GROUP_FIND_GROUP = "/group/findGroup";  // 根据组织查班组


// 塔机设备接口
httpInterface.URL_DATA_DISPLAY = "/crane/dataDisplay";   // 单个塔机数据展示 首页
httpInterface.URL_FIND_PAGE = "/crane/findPage";  // 塔机分页查询
httpInterface.URL_INSERT_CRANE = "/crane/insertCrane";  // 塔机添加
httpInterface.URL_UPDATE_CRANE = "/crane/updateCrane";  // 修改塔机
httpInterface.URL_DELETE_BY_CRANE_ID = "/crane/deleteByCraneId";  // 删除塔机
httpInterface.URL_SELECT_BY_CRANE_ID = "/crane/selectByCraneId";  // 查询对应 id 塔机

export default httpInterface;
